﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using EXCEL = Microsoft.Office.Interop.Excel;

namespace PiaExcel
{
    #region PiaWorkBook对象
    /// <summary>
    /// PiaWorkbook对象
    /// </summary>
    public class PiaWorkbook
    {
        internal PiaExcelApp excelApp = PiaExcelApp.Create();
        internal EXCEL.Workbook mWorkBook;

        /// <summary>
        /// PiaWorkBook构造函数
        /// </summary>
        /// <param name="path"></param>
        public PiaWorkbook(string path)
        {
            this.Path = path;
            if (this.IsExists())
            {
                excelApp.ExcelApplication.Visible = true;
                this.ExcelWorkBook = excelApp.ExcelApplication.Workbooks.Open(this.Path);
            }
            else
            {
                throw new FileNotFoundException();
            }

        }

        /// <summary>
        /// 返回原生态WorkBook对象
        /// </summary>
        public EXCEL.Workbook ExcelWorkBook
        {
            private set
            {
                mWorkBook = value;
            }
            get
            {
                return mWorkBook;
            }
        }

        /// <summary>
        /// 文件路径
        /// </summary>
        public string Path
        {
            get;
            set;
        }

        /// <summary>
        /// 确定指定文件是否存在
        /// </summary>
        /// <returns></returns>
        public bool IsExists()
        {
            return File.Exists(this.Path);
        }


        /// <summary>
        /// 关闭当前WorkBook
        /// </summary>
        public void Close()
        {
            this.ExcelWorkBook.Close();
        }

        /// <summary>
        /// WorkBook Save方法
        /// </summary>
        public void Save()
        {
            this.ExcelWorkBook.Save();
        }

        /// <summary>
        /// WorkBook SaveAs方法
        /// </summary>
        public void SaveAs()
        {
            this.ExcelWorkBook.SaveAs();
        }

        /// <summary>
        /// 返回PiaWorkSheet对象
        /// </summary>
        /// <param name="workSheetName">workSheet名</param>
        /// <returns></returns>
        public PiaWorkSheet WorkSheet(string workSheetName)
        {
            PiaWorkSheet ws = new PiaWorkSheet(mWorkBook.Worksheets[workSheetName]);
            return ws;
        }

        /// <summary>
        /// 返回PiaWorkSheet对象
        /// </summary>
        /// <param name="index">workSheet索引号</param>
        /// <returns></returns>
        public PiaWorkSheet WorkSheet(int index)
        {
            return this.mWorkBook.Sheets[index];
        }
    }
    #endregion
}
